import 'dotenv/config'
import axios from "axios";
import { redisGet, redisSet } from '../common/redis';

const {
    FEISHU_API_URL: feishuApi,
    FEISHU_APP_ID: app_id,
    FEISHU_APP_SECRET: app_secret,
} = process.env;

export async function getTenantAccessToken() {
    const access_token = await redisGet("feishu_tenant_access_token")
    if (access_token) return access_token;

    const { data: { msg, tenant_access_token, expire } } = await axios.post(
        `${feishuApi}/auth/v3/tenant_access_token/internal`,
        { app_id, app_secret }
    );
    if (msg != 'ok') throw Error(msg)

    await redisSet("feishu_tenant_access_token", tenant_access_token , expire)
    return tenant_access_token;
}
